/**
 * 认证提示Modal组件
 * 提供友好的登录提示和渐进式引导
 */

import React, { useState, useEffect } from 'react';
import { Modal, Button, Space, Typography } from 'antd';
import { LoginOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { AUTH_MODAL_CONFIG, saveRedirectPath } from '../config/authConfig';

const { Text } = Typography;

interface AuthModalProps {
  visible: boolean;
  onClose: () => void;
  title?: string;
  content?: string;
  showCountdown?: boolean;
  onLogin?: () => void;
  isSessionExpired?: boolean;
}

const AuthModal: React.FC<AuthModalProps> = ({
  visible,
  onClose,
  title = AUTH_MODAL_CONFIG.DEFAULT_TITLE,
  content = AUTH_MODAL_CONFIG.DEFAULT_CONTENT,
  showCountdown = AUTH_MODAL_CONFIG.SHOW_COUNTDOWN,
  onLogin,
  isSessionExpired = false
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [countdown, setCountdown] = useState(AUTH_MODAL_CONFIG.AUTO_REDIRECT_COUNTDOWN);
  const [isCountingDown, setIsCountingDown] = useState(false);

  // 处理倒计时
  useEffect(() => {
    if (visible && showCountdown && isSessionExpired) {
      setIsCountingDown(true);
      setCountdown(AUTH_MODAL_CONFIG.AUTO_REDIRECT_COUNTDOWN);
    } else {
      setIsCountingDown(false);
    }
  }, [visible, showCountdown, isSessionExpired]);

  useEffect(() => {
    if (isCountingDown && countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (isCountingDown && countdown === 0) {
      handleLogin();
    }
  }, [isCountingDown, countdown]);

  // 处理登录
  const handleLogin = () => {
    // 保存当前路径
    saveRedirectPath(location.pathname + location.search);
    
    if (onLogin) {
      onLogin();
    } else {
      navigate('/login');
    }
    
    onClose();
  };

  // 处理稍后再说
  const handleLater = () => {
    setIsCountingDown(false);
    onClose();
  };

  // 获取显示的标题和内容
  const displayTitle = isSessionExpired 
    ? AUTH_MODAL_CONFIG.SESSION_EXPIRED_TITLE 
    : title;
  
  const displayContent = isSessionExpired 
    ? AUTH_MODAL_CONFIG.SESSION_EXPIRED_CONTENT 
    : content;

  return (
    <Modal
      title={
        <Space>
          <LoginOutlined style={{ color: '#1890ff' }} />
          <span>{displayTitle}</span>
        </Space>
      }
      open={visible}
      onCancel={handleLater}
      footer={
        <Space style={{ width: '100%', justifyContent: 'space-between' }}>
          <div>
            {isCountingDown && (
              <Space>
                <ClockCircleOutlined />
                <Text type="secondary">
                  {countdown}秒后自动跳转到登录页
                </Text>
              </Space>
            )}
          </div>
          <Space>
            <Button onClick={handleLater}>
              稍后再说
            </Button>
            <Button type="primary" icon={<LoginOutlined />} onClick={handleLogin}>
              立即登录
            </Button>
          </Space>
        </Space>
      }
      centered
      maskClosable={false}
      width={480}
    >
      <div style={{ padding: '20px 0' }}>
        <Text>{displayContent}</Text>
        {!isSessionExpired && (
          <div style={{ marginTop: 16 }}>
            <Text type="secondary">
              登录后您可以：
            </Text>
            <ul style={{ marginTop: 8, paddingLeft: 20 }}>
              <li>访问所有功能模块</li>
              <li>保存和管理您的数据</li>
              <li>查看历史操作记录</li>
              <li>获得完整的系统权限</li>
            </ul>
          </div>
        )}
      </div>
    </Modal>
  );
};

// 导出一个便捷的显示方法
let authModalInstance: any = null;

export const showAuthModal = (props?: Partial<AuthModalProps>) => {
  if (authModalInstance) {
    authModalInstance.destroy();
  }

  const defaultProps: AuthModalProps = {
    visible: true,
    onClose: () => {
      if (authModalInstance) {
        authModalInstance.destroy();
        authModalInstance = null;
      }
    },
    ...props
  };

  authModalInstance = Modal.confirm({
    title: (
      <Space>
        <LoginOutlined style={{ color: '#1890ff' }} />
        <span>{defaultProps.title || AUTH_MODAL_CONFIG.DEFAULT_TITLE}</span>
      </Space>
    ),
    content: defaultProps.content || AUTH_MODAL_CONFIG.DEFAULT_CONTENT,
    okText: '立即登录',
    cancelText: '稍后再说',
    icon: null,
    centered: true,
    maskClosable: false,
    onOk: () => {
      if (defaultProps.onLogin) {
        defaultProps.onLogin();
      } else {
        // 保存当前路径并跳转到登录页
        saveRedirectPath(window.location.pathname + window.location.search);
        window.location.href = '/#/login';
      }
    },
    onCancel: defaultProps.onClose
  });

  return authModalInstance;
};

export default AuthModal;